In [1]:
import pandas as pd
import plotly.express as px
from sklearn import datasets
In [2]:
# import iris data
iris = datasets.load_iris()

X = pd.DataFrame(iris.data,columns=iris.feature_names )
y = pd.DataFrame(iris.target,columns=['Target'] )
y['Target'] = y['Target'].map(dict(zip(list(y['Target'].unique()), list(iris.target_names))))
data = pd.concat([X,y],axis=1)
data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   sepal length (cm)  150 non-null    float64
 1   sepal width (cm)   150 non-null    float64
 2   petal length (cm)  150 non-null    float64
 3   petal width (cm)   150 non-null    float64
 4   Target             150 non-null    object 
dtypes: float64(4), object(1)
memory usage: 6.0+ KB
In [3]:
# Obtain the dataframe that will be in the body of the email
df_body = data.groupby('Target')['sepal length (cm)'].describe()
df_body = df_body.reset_index()
In [4]:
# To send the dataframe in the body, we need the convert it to html format.
# To get a better visualisation for the DataFrame in html, I often use 'build_table'
from pretty_html_table import build_table

body_html_table = build_table(df_body, 'blue_light', text_align='left',index=False, font_size='small')
In [5]:
export_location = 'C:\\Users\\mert.eygi\\SendSMTPEmail\\'
In [6]:
# Obtain the plots that will be in the body of the email
plot_names = []
for fn in iris.feature_names:
    plot_name = fn+'.jpg'
    fig = px.box(data,x='Target', y=fn, title = fn + ' for each Target',width=600, height=500)
    fig.write_image(export_location + plot_name)
    plot_names.append(plot_name)
#Just show the last one
fig.show()
print(f'created plot names:\n{plot_names}')
created plot names:
['sepal length (cm).jpg', 'sepal width (cm).jpg', 'petal length (cm).jpg', 'petal width (cm).jpg']
In [7]:
#Obtain the files that will be attached of the email.
file_names = ['iris_data_1.xlsx','iris_data_2.xlsx']

#First File
data.to_excel(export_location + file_names[0],index=False)

#Second File
data.to_excel(export_location + file_names[1],index=False)
In [8]:
#Your Gmail informations
sender_email = 'YOUR_GMAIL_ACCOUNT'
email_app_pass = 'YOUR_GMAIL_APP_PASSWORD'

#email recipients
email_to = 'merteygi@gmail.com,mert.eygi@marsathletic.com' # You can write by separating the recipients with a comma(,)
#email recipients
email_subject = 'SMTP_EMAIL_EXAMPLE'
In [9]:
##################################################
#################  SEND MAIL #####################
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email import encoders


msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = email_to
msg['Subject'] = email_subject


msgText = MIMEText('Hello,''<br>''<br>'
                    '<b>This is the body of the email, you can write anything in it</b><br>'
                   'The desired dataframe will be shown below <br>'
                    + body_html_table+'<br>'
                   '<br>''Plot-1  will be shown below <br>'
                   '<img src="cid:image_0">'
                   
                   '<br>''Plot-2 will be shown below <br>'
                   '<img src="cid:image_1">'
                   
                   '<br>''Plot-3 will be shown below <br>'
                   '<img src="cid:image_2">'
                   
                   '<br>''Plot-4 will be shown below <br>'
                   '<img src="cid:image_3">'
                   
                   '<br>'
                   '<br>'
                   'for your information.'
                   '<br>'
                   'Mert Eygi', 'html')
msg.attach(msgText)


for i, plot_name in enumerate(plot_names):
    fp = open(export_location + plot_name, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID', '<image_'+str(i)+'>')
    msg.attach(msgImage)


for i, file_name in enumerate(file_names):
    attachment = open(export_location + file_name, 'rb')
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % file_name)
    msg.attach(part)


server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(sender_email, email_app_pass)
text = msg.as_string()
server.sendmail(msg['From'], msg['To'].split(","), msg.as_string())
print('Email Sent')
server.quit()
#################  SEND MAIL #####################
##################################################
Email Sent
Out[9]:
(221,
 b'2.0.0 closing connection f20-20020a17090631d400b0078a543e9301sm1436894ejf.200 - gsmtp')